//
//  NSString+Extension.m
//  JiLaiBao
//
//  Created by youmy on 15/10/9.
//  Copyright (c) 2015年 youmy. All rights reserved.
//

#import "NSString+Extension.h"
#import <sys/utsname.h>
#import <ifaddrs.h>
#import <arpa/inet.h>
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonHMAC.h>
#define CC_LEN_FOR_TYPE		4	// number of characters to determine length
static NSBundle *bundle = nil;
@implementation NSString (Extension)
+ (NSString *)cleanNumber:(NSString *)str
{
    return [str stringByReplacingOccurrencesOfString:@" " withString:@""];
}

+ (CGSize)boundingRectWithString:(NSString *)string font:(UIFont *)font width:(CGFloat)width{
    NSMutableDictionary * attr = [NSMutableDictionary dictionary];
    attr[NSFontAttributeName] = font;
    CGSize maxSize = CGSizeMake(width, MAXFLOAT);
    CGSize size = [string boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attr context:nil].size;
    return size;
}

+ (CGSize)boundingRectWithString:(NSString *)string font:(UIFont *)font height:(CGFloat)height{
    NSMutableDictionary * attr = [NSMutableDictionary dictionary];
    attr[NSFontAttributeName] = font;
    CGSize maxSize = CGSizeMake(MAXFLOAT, height);
    CGSize size = [string boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attr context:nil].size;
    return size;
}

+ (CGSize)boundingRectWithString:(NSString *)string font:(UIFont *)font{
    NSMutableDictionary * attr = [NSMutableDictionary dictionary];
    attr[NSFontAttributeName] = font;
    CGSize maxSize = CGSizeMake(MAXFLOAT, MAXFLOAT);
    CGSize size = [string boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attr context:nil].size;
    return size;
}

+ (NSString *)formatterCurrency:(NSString *)currency{
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    formatter.numberStyle = NSNumberFormatterDecimalStyle;
    NSString *remainingString = [formatter stringFromNumber:[NSNumber numberWithInt:currency.intValue]];
    return [remainingString stringByAppendingString:@".00"];
}

+ (NSString *)formatterCurrencyWithCGflot:(NSString *)currency{
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    formatter.numberStyle = NSNumberFormatterDecimalStyle;
    NSString *remainingString = [formatter stringFromNumber:[NSNumber numberWithInt:currency.intValue]];
    return remainingString;
}

+ (NSString *)deviceType{
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString * model = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    if ([model isEqualToString:@"iPhone3,1"]) return @"iPhone 4";
    if ([model isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
    if ([model isEqualToString:@"iPhone5,1"]||[model isEqualToString:@"iPhone5,2"]||[model isEqualToString:@"iPhone5,3"]||[model isEqualToString:@"iPhone5,4"]||[model isEqualToString:@"iPhone6,1"]||[model isEqualToString:@"iPhone6,2"]) return @"iPhone 5";
    if ([model isEqualToString:@"iPhone7,2"]||
        [model isEqualToString:@"iPhone8,1"]) return @"iPhone 6";
    if ([model isEqualToString:@"iPhone7,1"]||
        [model isEqualToString:@"iPhone8,2"]) return @"iPhone 6P";
    return @"iPhone SE";
}


+ (NSString*)deviceVersion
{
    // 需要#import "sys/utsname.h"
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    
    //iPhone
    if ([deviceString isEqualToString:@"iPhone1,1"])    return @"iPhone 1G";
    if ([deviceString isEqualToString:@"iPhone1,2"])    return @"iPhone 3G";
    if ([deviceString isEqualToString:@"iPhone2,1"])    return @"iPhone 3GS";
    if ([deviceString isEqualToString:@"iPhone3,1"])    return @"iPhone 4";
    if ([deviceString isEqualToString:@"iPhone3,2"])    return @"Verizon iPhone 4";
    if ([deviceString isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
    if ([deviceString isEqualToString:@"iPhone5,1"])    return @"iPhone 5";
    if ([deviceString isEqualToString:@"iPhone5,2"])    return @"iPhone 5";
    if ([deviceString isEqualToString:@"iPhone5,3"])    return @"iPhone 5C";
    if ([deviceString isEqualToString:@"iPhone5,4"])    return @"iPhone 5C";
    if ([deviceString isEqualToString:@"iPhone6,1"])    return @"iPhone 5S";
    if ([deviceString isEqualToString:@"iPhone6,2"])    return @"iPhone 5S";
    if ([deviceString isEqualToString:@"iPhone7,1"])    return @"iPhone 6 Plus";
    if ([deviceString isEqualToString:@"iPhone7,2"])    return @"iPhone 6";
    if ([deviceString isEqualToString:@"iPhone8,1"])    return @"iPhone 6s";
    if ([deviceString isEqualToString:@"iPhone8,2"])    return @"iPhone 6s Plus";
    
    if ([deviceString isEqualToString:@"iPhone9,1"])    return @"iPhone 7";
    if ([deviceString isEqualToString:@"iPhone9,2"])    return @"iPhone 7 Plus";
    //iPod
    if ([deviceString isEqualToString:@"iPod1,1"])      return @"iPod Touch 1G";
    if ([deviceString isEqualToString:@"iPod2,1"])      return @"iPod Touch 2G";
    if ([deviceString isEqualToString:@"iPod3,1"])      return @"iPod Touch 3G";
    if ([deviceString isEqualToString:@"iPod4,1"])      return @"iPod Touch 4G";
    if ([deviceString isEqualToString:@"iPod5,1"])      return @"iPod Touch 5G";
    
    //iPad
    if ([deviceString isEqualToString:@"iPad1,1"])      return @"iPad";
    if ([deviceString isEqualToString:@"iPad2,1"])      return @"iPad 2 (WiFi)";
    if ([deviceString isEqualToString:@"iPad2,2"])      return @"iPad 2 (GSM)";
    if ([deviceString isEqualToString:@"iPad2,3"])      return @"iPad 2 (CDMA)";
    if ([deviceString isEqualToString:@"iPad2,4"])      return @"iPad 2 (32nm)";
    if ([deviceString isEqualToString:@"iPad2,5"])      return @"iPad mini (WiFi)";
    if ([deviceString isEqualToString:@"iPad2,6"])      return @"iPad mini (GSM)";
    if ([deviceString isEqualToString:@"iPad2,7"])      return @"iPad mini (CDMA)";
    
    if ([deviceString isEqualToString:@"iPad3,1"])      return @"iPad 3(WiFi)";
    if ([deviceString isEqualToString:@"iPad3,2"])      return @"iPad 3(CDMA)";
    if ([deviceString isEqualToString:@"iPad3,3"])      return @"iPad 3(4G)";
    if ([deviceString isEqualToString:@"iPad3,4"])      return @"iPad 4 (WiFi)";
    if ([deviceString isEqualToString:@"iPad3,5"])      return @"iPad 4 (4G)";
    if ([deviceString isEqualToString:@"iPad3,6"])      return @"iPad 4 (CDMA)";
    
    if ([deviceString isEqualToString:@"iPad4,1"])      return @"iPad Air";
    if ([deviceString isEqualToString:@"iPad4,2"])      return @"iPad Air";
    if ([deviceString isEqualToString:@"iPad4,3"])      return @"iPad Air";
    if ([deviceString isEqualToString:@"iPad5,3"])      return @"iPad Air 2";
    if ([deviceString isEqualToString:@"iPad5,4"])      return @"iPad Air 2";
    if ([deviceString isEqualToString:@"i386"])         return @"Simulator";
    if ([deviceString isEqualToString:@"x86_64"])       return @"Simulator";
    
    if ([deviceString isEqualToString:@"iPad4,4"]
        ||[deviceString isEqualToString:@"iPad4,5"]
        ||[deviceString isEqualToString:@"iPad4,6"])      return @"iPad mini 2";
    
    if ([deviceString isEqualToString:@"iPad4,7"]
        ||[deviceString isEqualToString:@"iPad4,8"]
        ||[deviceString isEqualToString:@"iPad4,9"])      return @"iPad mini 3";
    
    return deviceString;
}

+ (NSString *)deviceTypeHeight{
    if (SCREEN_HEIGHT == 480) {
        return @"iPhone 4/4S";
    }
    
    if (SCREEN_HEIGHT == 568) {
        return @"iPhone 5/5C/5S/SE";
    }
    
    if (SCREEN_HEIGHT == 667) {
        return @"iPhone 6/6S";
    }
    
    if (SCREEN_HEIGHT == 736) {
        return @"iPhone 6 PLUS/6S PLUS";
    }
    return @"";
}

+ (BOOL)getcurrentNetStatus{
    if ([[self networkingStatusFromStatusbar] isEqualToString:@"notReachable"]) return NO;
    return YES;
}

#pragma mark - 检测网络状态
+ (NSString *)networkingStatusFromStatusbar {
    // 状态栏是由当前app控制的，首先获取当前app
    UIApplication *app = [UIApplication sharedApplication];
    NSArray *children = [[[app valueForKeyPath:@"statusBar"] valueForKeyPath:@"foregroundView"] subviews];
    int type = 0;
    for (id child in children) {
        if ([child isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]])
        {
            type = [[child valueForKeyPath:@"dataNetworkType"] intValue];
        }
    }
    NSString *stateString = @"wifi";
    switch (type) {
        case 0:
            stateString = @"notReachable";
            break;
        case 1:
            stateString = @"2G";
            break;
        case 2:
            stateString = @"3G";
            break;
        case 3:
            stateString = @"4G";
            break;
        case 4:
            stateString = @"LTE";
            break;
        case 5:
            stateString = @"wifi";
            break;
        default:
            break;
    }
    return stateString;
}

// Get IP Address
+ (NSString *)getIPAddress{
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    // Free memory
    freeifaddrs(interfaces);
    return address;
}

+ (NSString *)getVersion{
    NSString * key = @"CFBundleVersion";
    NSString * currentVersion = [NSBundle mainBundle].infoDictionary[key];
    return currentVersion;
}

+ (NSString *)getShortVersion{
    NSString * key = @"CFBundleShortVersionString";
    NSString * currentVersion = [NSBundle mainBundle].infoDictionary[key];
    return currentVersion;
}

+ (NSDictionary *)getInfoDictionary{
    NSDictionary * dic = [NSBundle mainBundle].infoDictionary;
    return dic;
}

+ (NSString*)timeformatFromSeconds:(NSInteger)seconds
{
    //format of hour
    NSString *str_hour = [NSString stringWithFormat:@"%02ld",seconds/3600];
    //format of minute
    NSString *str_minute = [NSString stringWithFormat:@"%02ld",(seconds%3600)/60];
    //format of second
    NSString *str_second = [NSString stringWithFormat:@"%02ld",seconds%60];
    //format of time
    NSString *format_time = [NSString stringWithFormat:@"%@:%@:%@",str_hour,str_minute,str_second];
    return format_time;
}

+ (NSString*)timeformatForCNFromSeconds:(NSInteger)seconds
{
    //format of hour
    NSString *str_hour = [NSString stringWithFormat:@"%02ld",seconds/3600];
    //format of minute
    NSString *str_minute = [NSString stringWithFormat:@"%02ld",(seconds%3600)/60];
    //format of second
    NSString *str_second = [NSString stringWithFormat:@"%02ld",seconds%60];
    
    //format of time
    NSString *format_time = [NSString stringWithFormat:@"%@:%@:%@",str_hour,str_minute,str_second];
    
    if ([str_hour isEqualToString:@"00"]) {
        if ([str_minute isEqualToString:@"00"]) {
            if ([str_second isEqualToString:@"00"]) format_time = @"";
            format_time = [NSString stringWithFormat:@"%@秒",str_second];
        }else{
            format_time = [NSString stringWithFormat:@"%@分%@秒",str_minute,str_second];
        }
    }else{
        format_time = [NSString stringWithFormat:@"%@小时%@分%@秒",str_hour,str_minute,str_second];
    }
    
    return format_time;
}


+ (NSDictionary *)resourcePathWithFileName:(NSString *)fileName{
    @try {
        NSString * path = [[NSBundle mainBundle].resourcePath stringByAppendingPathComponent:fileName];
        NSData * data = [NSData dataWithContentsOfFile:path];
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        return dic;
    } @catch (NSException *exception) {
        NSLog(@"%@-%@",exception.description,exception.userInfo);
    } @finally {
    }
}

+ (NSString *)dateWithString:(NSString *)dateStr formatter:(NSString *)formatterStr{
    NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSDate * date = [formatter dateFromString:dateStr];
    formatter.dateFormat = formatterStr;
    
    NSString * str = [formatter stringFromDate:date];
    
    return str;
}
//获取当前的时间
+(NSString*)getCurrentTimes{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    
    //现在时间,你可以输出来看下是什么格式
    
    NSDate *datenow = [NSDate date];
    
    //----------将nsdate按formatter格式转成nsstring
    
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    
    //NSLog(@"currentTimeString =  %@",currentTimeString);
    
    return currentTimeString;
 
}

/**
 得到当前时间
 @return NSDate
 */
+(NSString *)getCurrentTimeDate{
    // 获取代表公历的NSCalendar对象
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    // 获取当前日期
    NSDate* dt = [NSDate date];
    // 定义一个时间字段的旗标，指定将会获取指定年、月、日、时、分、秒的信息
    unsigned unitFlags = NSCalendarUnitYear |
    NSCalendarUnitMonth |  NSCalendarUnitDay |
    NSCalendarUnitHour |  NSCalendarUnitMinute |
    NSCalendarUnitSecond | NSCalendarUnitWeekday;
    // 获取不同时间字段的信息
    NSDateComponents* comp = [gregorian components: unitFlags
                                          fromDate:dt];
    // 通过NSDateComponents所包含的时间字段的数值来恢复NSDate对象
    NSString *dateStr = [NSString stringWithFormat:@"%ld-%ld-%ld",comp.year,comp.month,comp.day];
    return dateStr;
}
+(NSString *)getCurrentTime{
    NSDate *currentDate = [NSDate date];//获取当前时间，日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY/MM/dd hh:mm:ss"];
    NSString *dateString = [dateFormatter stringFromDate:currentDate];
    return dateString;

}

/**
 获取当前时间的时间戳

 @return 时间戳
 */
+(NSString *)GetTheTimestampOfTheCurrentTime{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setTimeZone:timeZone];
    
    NSDate *datenow = [NSDate date];
    
    NSString *nowtimeStr = [formatter stringFromDate:datenow];
    
    NSDate* date = [formatter dateFromString:nowtimeStr]; //------------将字符串按formatter转成nsdate
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[date timeIntervalSince1970]];
        //NSLog(@"timeSp:%@",timeSp); //时间戳的值
    //NSLog(@"nowtimeStr:%@",nowtimeStr); //时间戳的值
    return timeSp;
}
+(NSString *)changeTimeStrWithStr:(NSString *)time{
    
    NSString* timeStr = time;
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setTimeZone:timeZone];
    
    NSDate* date = [formatter dateFromString:timeStr]; //------------将字符串按formatter转成nsdate

    //时间转时间戳的方法:
    NSString *timeSp = [NSString stringWithFormat:@"%f",[date timeIntervalSince1970]];
    //NSLog(@"timeSp:%@",timeSp); //时间戳的值
    return timeSp;
}


/**
 时间戳转时间

 @param timeString 1498208338000
 @return 2017-06-27
 */
+(NSString *)timeWithTimeIntervalString:(NSString *)timeString
{
    // 格式化时间
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; 
    
    // 毫秒值转化为秒
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:[timeString doubleValue]/ 1000.0];
    NSString* dateString = [formatter stringFromDate:date];
    return dateString;
}

+(NSString *)timestamp2MonthMinute:(NSString *)timestamp
{
    // 格式化时间
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"MM月dd日  HH:mm"];
    
    // 毫秒值转化为秒
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:[timestamp doubleValue]/ 1000.0];
    NSString* dateString = [formatter stringFromDate:date];
    return dateString;
}

/**
 时间戳转小时分钟
 
 @param timeString 1498208338000
 @return 07:00
 */
+(NSString *)getHourMinuteWithString:(NSString *)timeString
{
    // 格式化时间
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"HH:mm"];
    
    // 毫秒值转化为秒
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:[timeString doubleValue]];
    NSString* dateString = [formatter stringFromDate:date];
    return dateString;
}
/**
 时间戳转分钟
 
 @param timeString 1498208338000
 @return 07:00
 */
+(NSString *)getMinuteWithString:(NSString *)timeString
{
    // 格式化时间
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"mm"];
    
    // 毫秒值转化为秒
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:[timeString doubleValue]];
    NSString* dateString = [formatter stringFromDate:date];
    return dateString;
}
+(NSString *)getCurrentTimeSp{
    
    NSDateFormatter * formatter = [[NSDateFormatter alloc ] init];
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss:SSS"];
    NSString *date =  [formatter stringFromDate:[NSDate date]];
    NSString *timeLocal = [[NSString alloc] initWithFormat:@"%@", date];
    NSLog(@"%@", timeLocal);
    return timeLocal;
}

/**
 将现在的时间与指定时间比较，如果没达到指定日期，返回-1，刚好是这一时间，返回0，否则返回1

 @param oneDay 现在时间
 @param anotherDay 指定日期
 @return true/false
 */
+(int)compareOneDay:(NSDate *)oneDay withAnotherDay:(NSDate *)anotherDay
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd-MM-yyyy-HHmmss"];
    NSString *oneDayStr = [dateFormatter stringFromDate:oneDay];
    NSString *anotherDayStr = [dateFormatter stringFromDate:anotherDay];
    NSDate *dateA = [dateFormatter dateFromString:oneDayStr];
    NSDate *dateB = [dateFormatter dateFromString:anotherDayStr];
    NSComparisonResult result = [dateA compare:dateB];
    NSLog(@"date1 : %@, date2 : %@", oneDay, anotherDay);
    if (result == NSOrderedDescending) {
        //NSLog(@"Date1  is in the future");
        return 1;
    }
    else if (result == NSOrderedAscending){
        //NSLog(@"Date1 is in the past");
        return -1;
    }
    //NSLog(@"Both dates are the same");
    return 0;
    
}
/**
 提醒弹窗
 */
+(void)setstateWithProgress{
    
    [SVProgressHUD setBackgroundColor:[UIColor whiteColor]];
    [SVProgressHUD setMinimumSize:CGSizeMake(100, 35)];
    [SVProgressHUD setMinimumDismissTimeInterval:3];
    [SVProgressHUD setMaximumDismissTimeInterval:4];
    //[self showImage:[UIImage imageNamed:@"icon_develop"] text:@"开发中···"];
}


/**
 ios通过图片的URL地址，从网络上获取图片(UIImage类型)

 @param fileURL 图片url
 @return uiimage
 */
+(UIImage *)getImageFromURL:(NSString *)fileURL
{
    
    UIImage * result;
    NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
    result = [UIImage imageWithData:data];
    return result;
}

/**
 判断是不是数字
 */
+ (BOOL)deptNumInputShouldNumber:(NSString *)str
{
    NSString *regex = @"[0-9]*";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    if ([pred evaluateWithObject:str]) {
        return YES;
    }
    return NO;
}

+ (UIViewController *)topViewController {
    UIViewController *resultVC;
    resultVC = [self _topViewController:[[UIApplication sharedApplication].keyWindow rootViewController]];
    while (resultVC.presentedViewController) {
        resultVC = [self _topViewController:resultVC.presentedViewController];
    }
    return resultVC;
}

+ (UIViewController *)_topViewController:(UIViewController *)vc {
    if ([vc isKindOfClass:[UINavigationController class]]) {
        return [self _topViewController:[(UINavigationController *)vc topViewController]];
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        return [self _topViewController:[(UITabBarController *)vc selectedViewController]];
    } else {
        return vc;
    }
    return nil;
}
/**
 *  手机型号
 *
 *  @return e.g. iPhone
 */
+(NSString *)phoneModel{
    return [[UIDevice currentDevice] model];
}
/**
 手机别名*/
+(NSString *)phoneName
{
    return [[UIDevice currentDevice] name];
}


/**
 *  手机系统版本
 *
 *  @return e.g. 8.0
 */
+(NSString *)phoneVersion{
    return [[UIDevice currentDevice] systemVersion];
}

/**
 获取当前时间戳
 */
+(NSString *)getCurrentDate{
    NSDate *currentDate = [NSDate date];//获取当前时间，日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY/MM/dd hh:mm:ss"];
    NSString *dateString = [dateFormatter stringFromDate:currentDate];
    return dateString;
}

/**
 bundle是一个目录,其中包含了程序会使用到的资源
 */
+(NSDictionary *)getBundleInfo{
    //app应用相关信息的获取
    NSDictionary *dicInfo = [[NSBundle mainBundle] infoDictionary];
    return dicInfo;
}

+ (UIButton *)createBBI:(CGRect)frame title:(NSString *)title image:(NSString *)image target:(id)target selector:(SEL)sel
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = frame;
    btn.titleLabel.font = [UIFont systemFontOfSize:14];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageNamed:image] forState:UIControlStateNormal];
    [btn addTarget:target action:sel forControlEvents:UIControlEventTouchUpInside];
    
    return btn;
}

+(UIButton *)createButton:(CGRect)frame title:(NSString *)title image:(UIImage *)image target:(id)target selector:(SEL)selector
{
    UIButton * button=[UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:image forState:UIControlStateNormal];
    button.frame=frame;
    CGRect newFrame=frame;
    newFrame.origin.y=frame.size.height/2.0;
    newFrame.size.height=frame.size.height/2.0;
    newFrame.origin.x=0;
    UILabel * label=[[UILabel alloc]initWithFrame:newFrame];
    label.text=title;
    [button addSubview:label];
    label.font=[UIFont systemFontOfSize:12];
    label.backgroundColor=[UIColor clearColor];
    [button addTarget:target action:selector forControlEvents:UIControlEventTouchUpInside];
    return button;
}

+(CGFloat)widthOfString:(NSString *)string font:(UIFont *)font height:(CGFloat)height
{
    NSDictionary * dict=[NSDictionary dictionaryWithObject: font forKey:NSFontAttributeName];
    CGRect rect=[string boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, height) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil];
    return rect.size.width;
}

+(CGFloat)heightOfString:(NSString *)string font:(UIFont *)font width:(CGFloat)width
{
    CGRect bounds;
    NSDictionary * parameterDict=[NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
    bounds=[string boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:parameterDict context:nil];
    return bounds.size.height;
}

#pragma  mark - 获取当天的日期：年月日
+ (NSDictionary *)getTodayDate
{
    //获取今天的日期
    NSDate *today = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSCalendarUnit unit = kCFCalendarUnitYear|kCFCalendarUnitMonth|kCFCalendarUnitDay|kCFCalendarUnitHour|kCFCalendarUnitMinute;
    
    NSDateComponents *components = [calendar components:unit fromDate:today];
    NSString *year = [NSString stringWithFormat:@"%ld", (long)[components year]];
    NSString *month = [NSString stringWithFormat:@"%02ld", (long)[components month]];
    NSString *day = [NSString stringWithFormat:@"%02ld", (long)[components day]];
    NSString *hour = [NSString stringWithFormat:@"%02ld", (long)[components hour]];
    NSString *minute = [NSString stringWithFormat:@"%02ld", (long)[components minute]];
    NSMutableDictionary *todayDic = [[NSMutableDictionary alloc] init];
    [todayDic setObject:year forKey:@"year"];
    [todayDic setObject:month forKey:@"month"];
    [todayDic setObject:day forKey:@"day"];
    [todayDic setObject:hour forKey:@"hour"];
    [todayDic setObject:minute forKey:@"minute"];
    return todayDic;
}


#pragma  mark - 时间比较
+(NSString *)compareFromDate:(NSDate *)from toDate:(NSDate *)to
{
    if (!to || !from) {
        return @"";
    }
    
    // 日历
    NSCalendar * calendar = [NSCalendar currentCalendar];
    
    // 时间片段 ：年  月  日  时 分 秒
    int unit = NSCalendarUnitYear | NSCalendarUnitMonth  | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    
    NSDateComponents * com = [calendar components:unit fromDate:from toDate:to options:0];
    
    NSString *string = [NSString stringWithFormat:@"剩余%ld小时%ld分钟", (long)com.hour, (long)com.minute];
    
    return string;
}
//时间戳
+(NSString *)getTimestampWithString:(NSString *)str{
    
    NSTimeInterval time=[str doubleValue]/1000;//因为时差问题要加8小时 == 28800 sec
    
    NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time];
    
    //实例化一个NSDateFormatter对象
    NSDateFormatter*dateFormatter = [[NSDateFormatter alloc]init];
    
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSString*currentDateStr = [dateFormatter stringFromDate:detaildate];
    return currentDateStr;
}

//邮箱
+ (BOOL)justEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}


//手机号码验证
+ (BOOL)justMobile:(NSString *)mobile
{
    //手机号以13， 15，18开头，八个 \d 数字字符
    //    电信号段:133/153/180/181/189/177
    //    联通号段:130/131/132/155/156/185/186/145/176
    //    移动号段:134/135/136/137/138/139/150/151/152/157/158/159/182/183/184/187/188/147/178
    //    虚拟运营商:170
    NSString *phoneRegex = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|7[06-8])\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
}

//车牌号验证
+ (BOOL)justCarNo:(NSString *)carNo
{
    NSString *carRegex = @"^[\u4e00-\u9fa5]{1}[a-zA-Z]{1}[a-zA-Z_0-9]{4}[a-zA-Z_0-9_\u4e00-\u9fa5]$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",carRegex];
    NSLog(@"carTest is %@",carTest);
    return [carTest evaluateWithObject:carNo];
}


//车型
+ (BOOL)justCarType:(NSString *)CarType
{
    NSString *CarTypeRegex = @"^[\u4E00-\u9FFF]+$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",CarTypeRegex];
    return [carTest evaluateWithObject:CarType];
}

//用户名
+ (BOOL)justUserName:(NSString *)name
{
    NSString *userNameRegex = @"^[A-Za-z0-9]{6,20}+$";
    NSPredicate *userNamePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",userNameRegex];
    BOOL B = [userNamePredicate evaluateWithObject:name];
    return B;
}

//密码
+ (BOOL)justPassword:(NSString *)passWord
{
    NSString *passWordRegex = @"^[a-zA-Z0-9]{6,20}+$";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passWordRegex];
    return [passWordPredicate evaluateWithObject:passWord];
}

//昵称
+ (BOOL)justNickname:(NSString *)nickname
{
    NSString *nicknameRegex = @"^[\u4e00-\u9fa5]{4,8}$";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",nicknameRegex];
    return [passWordPredicate evaluateWithObject:nickname];
}

//身份证号
+ (BOOL)justIdentityCard: (NSString *)identityCard
{
    BOOL flag;
    if (identityCard.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:identityCard];
}
+(BOOL)checkUserID:(NSString *)userID
{
    //长度不为18的都排除掉
    if (userID.length!=18) {
        return NO;
    }
    
    //校验格式
    NSString *regex2 = @"^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    BOOL flag = [identityCardPredicate evaluateWithObject:userID];
    
    if (!flag) {
        return flag;    //格式错误
    }else {
        //格式正确在判断是否合法
        
        //将前17位加权因子保存在数组里
        NSArray * idCardWiArray = @[@"7", @"9", @"10", @"5", @"8", @"4", @"2", @"1", @"6", @"3", @"7", @"9", @"10", @"5", @"8", @"4", @"2"];
        
        //这是除以11后，可能产生的11位余数、验证码，也保存成数组
        NSArray * idCardYArray = @[@"1", @"0", @"10", @"9", @"8", @"7", @"6", @"5", @"4", @"3", @"2"];
        
        //用来保存前17位各自乖以加权因子后的总和
        NSInteger idCardWiSum = 0;
        for(int i = 0;i < 17;i++)
        {
            NSInteger subStrIndex = [[userID substringWithRange:NSMakeRange(i, 1)] integerValue];
            NSInteger idCardWiIndex = [[idCardWiArray objectAtIndex:i] integerValue];
            
            idCardWiSum+= subStrIndex * idCardWiIndex;
            
        }
        
        //计算出校验码所在数组的位置
        NSInteger idCardMod=idCardWiSum%11;
        
        //得到最后一位身份证号码
        NSString * idCardLast= [userID substringWithRange:NSMakeRange(17, 1)];
        
        //如果等于2，则说明校验码是10，身份证号码最后一位应该是X
        if(idCardMod==2)
        {
            if([idCardLast isEqualToString:@"X"]||[idCardLast isEqualToString:@"x"])
            {
                return YES;
            }else
            {
                return NO;
            }
        }else{
            //用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
            if([idCardLast isEqualToString: [idCardYArray objectAtIndex:idCardMod]])
            {
                return YES;
            }
            else
            {
                return NO;
            }
        }
    }
}
/**
 创建静态变量bundle,获取bundle,不可以使用getbundle
 */
+(NSBundle *)bundle{
    return bundle;
}

/**
 userLanguage存储在NSUserDefaults 首次加载检测是否存在,不存在读取AppleLanguages,并赋值给userLanguage
 */
+(void)initUserLanguage{
    
    
    NSString *string = [YMSaveTool valueForKey:@"userLanguage"];
    if (string.length == 0) {
        //获取系统当前语言版本(中文zh-Hans 英文en)
        NSArray *languages = [YMSaveTool objectForKey:@"AppleLanguages"];
        NSString *currentLanguage = [languages objectAtIndex:0];
        string = currentLanguage;
        [YMSaveTool setObject:currentLanguage forKey:@"userLanguage"];
    }
    //2.获取文件路径
    NSString *path =[[NSBundle mainBundle]pathForResource:string ofType:@"lproj"];
    bundle = [NSBundle bundleWithPath:path];//生成bundle
}

/**
 获取当前应用语言方法
 */
+(void)setUserlanguage:(NSString *)language{
    
    NSString *path = [[NSBundle mainBundle]pathForResource:language ofType:@"lproj"];
    
    bundle = [NSBundle bundleWithPath:path];
    [YMSaveTool setValue:language forKey:@"userLanguage"];
}
+(NSString *)userLanguage{
    
    NSArray *langArr = [YMSaveTool valueForKey:@"AppleLanguages"];
    NSString *language = langArr.firstObject;
    return language;
}
/**
 判断是否是有效的中文名
 
 @param realName 名字
 @return 如果是在如下规则下符合的中文名则返回`YES`，否则返回`NO`
 限制规则：
 1. 首先是名字要大于2个汉字，小于8个汉字
 2. 如果是中间带`{•|·}`的名字，则限制长度15位（新疆人的名字有15位左右的，之前公司实名认证就遇到过），如果有更长的，请自行修改长度限制
 3. 如果是不带小点的正常名字，限制长度为8位，若果觉得不适，请自行修改位数限制
 *PS: `•`或`·`具体是那个点具体处理需要注意*
 */
+ (BOOL)isVaildRealName:(NSString *)realName
{
    
    NSRange range1 = [realName rangeOfString:@"·"];
    NSRange range2 = [realName rangeOfString:@"•"];
    if(range1.location != NSNotFound ||   // 中文 ·
       range2.location != NSNotFound )    // 英文 •
    {
        //一般中间带 `•`的名字长度不会超过15位，如果有那就设高一点
        if ([realName length] < 2 || [realName length] > 15)
        {
            return NO;
        }
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[\u4e00-\u9fa5]+[·•][\u4e00-\u9fa5]+$" options:0 error:NULL];
        
        NSTextCheckingResult *match = [regex firstMatchInString:realName options:0 range:NSMakeRange(0, [realName length])];
        
        NSUInteger count = [match numberOfRanges];
        
        return count == 1;
    }
    else
    {
        //一般正常的名字长度不会少于2位并且不超过8位，如果有那就设高一点
        if ([realName length] < 2 || [realName length] > 8) {
            return NO;
        }
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[\u4e00-\u9fa5]+$" options:0 error:NULL];
        
        NSTextCheckingResult *match = [regex firstMatchInString:realName options:0 range:NSMakeRange(0, [realName length])];
        
        NSUInteger count = [match numberOfRanges];
        
        return count == 1;
    }
}

// 银行卡号转正常号 － 去除4位间的空格
+(NSString *)bankNumToNormalNum:(NSString *)bankCardNumber
{
    return [bankCardNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
}
// 正常号转银行卡号 － 增加4位间的空格
+(NSString *)normalNumToBankNum:(NSString *)bankCardNumber
{
    NSUInteger size = bankCardNumber.length / 4;
    
    NSMutableArray *tmpStrArr = [[NSMutableArray alloc] init];
    for (int n = 0;n < size; n++)
    {
        [tmpStrArr addObject:[bankCardNumber substringWithRange:NSMakeRange(n*4, 4)]];
    }
    
    [tmpStrArr addObject:[bankCardNumber substringWithRange:NSMakeRange(size*4, (bankCardNumber.length % 4))]];
    
    bankCardNumber = [tmpStrArr componentsJoinedByString:@" "];
    
    return bankCardNumber;
}

/**验证银行卡*/
+ (BOOL) IsBankCard:(NSString *)cardNumber
{
    if(cardNumber.length==0)
    {
        return NO;
    }
    NSString *digitsOnly = @"";
    char c;
    for (int i = 0; i < cardNumber.length; i++)
    {
        c = [cardNumber characterAtIndex:i];
        if (isdigit(c))
        {
            digitsOnly =[digitsOnly stringByAppendingFormat:@"%c",c];
        }
    }
    int sum = 0;
    int digit = 0;
    int addend = 0;
    BOOL timesTwo = false;
    for (NSInteger i = digitsOnly.length - 1; i >= 0; i--)
    {
        digit = [digitsOnly characterAtIndex:i] - '0';
        if (timesTwo)
        {
            addend = digit * 2;
            if (addend > 9) {
                addend -= 9;
            }
        }
        else {
            addend = digit;
        }
        sum += addend;
        timesTwo = !timesTwo;
    }
    int modulus = sum % 10;
    return modulus == 0;
}
//iOS-OC根据时间戳获取距离现在的状态(刚刚,分钟前,今天,昨天)
+(NSString *)distanceTimeWithBeforeTime:(double)beTime
{
    NSTimeInterval now = [[NSDate date]timeIntervalSince1970];
    double distanceTime = now - beTime;
    NSString * distanceStr;
    
    NSDate * beDate = [NSDate dateWithTimeIntervalSince1970:beTime];
    NSDateFormatter * df = [[NSDateFormatter alloc]init];
    [df setDateFormat:@"HH:mm"];
    NSString * timeStr = [df stringFromDate:beDate];
    
    [df setDateFormat:@"dd"];
    NSString * nowDay = [df stringFromDate:[NSDate date]];
    NSString * lastDay = [df stringFromDate:beDate];
    
    if (distanceTime < 60) {//小于一分钟
        distanceStr = @"刚刚";
    }
    else if (distanceTime <60*60) {//时间小于一个小时
        distanceStr = [NSString stringWithFormat:@"%ld分钟前",(long)distanceTime/60];
    }
    else if(distanceTime <24*60*60 && [nowDay integerValue] == [lastDay integerValue]){//时间小于一天
        distanceStr = [NSString stringWithFormat:@"今天 %@",timeStr];
    }
    else if(distanceTime<24*60*60*2 && [nowDay integerValue] != [lastDay integerValue]){
        
        if ([nowDay integerValue] - [lastDay integerValue] ==1 || ([lastDay integerValue] - [nowDay integerValue] > 10 && [nowDay integerValue] == 1)) {
            distanceStr = [NSString stringWithFormat:@"昨天 %@",timeStr];
        }
        else{
            [df setDateFormat:@"MM-dd HH:mm"];
            distanceStr = [df stringFromDate:beDate];
        }
        
    }
    else if(distanceTime <24*60*60*365){
        [df setDateFormat:@"MM-dd HH:mm"];
        distanceStr = [df stringFromDate:beDate];
    }
    else{
        [df setDateFormat:@"yyyy-MM-dd HH:mm"];
        distanceStr = [df stringFromDate:beDate];
    }
    return distanceStr;
}
@end

//let CC_LEN_FOR_TYPE = 4	// number of characters to determine length
//
//extension String {
//    
//    public func cleanNumber(str:String) -> String {
//        return str.replacingOccurrences(of: " ", with: "")
//    }
//    
//    public func boundingRectWithStringFontWidth(string:String,font:UIFont,width:CGFloat) -> CGSize {
//        
//        let attr = NSMutableDictionary.init()
//        attr[NSFontAttributeName] = font
//        
//        let statusLabelText: String = string
//        
//        let maxSize = CGSize(width:width, height:CGFloat(MAXFLOAT))
//        
//        let strSize = statusLabelText.boundingRect(with: maxSize, options: .usesLineFragmentOrigin, attributes: attr as? [String : AnyObject], context:nil).size
//        return strSize
//    }
//    public func boundingRectWithStringFontHeight(string:String,font:UIFont,height:CGFloat) -> CGSize {
//        
//        let attr = NSMutableDictionary.init()
//        attr[NSFontAttributeName] = font
//        
//        let statusLabelText: String = string
//        
//        let maxSize = CGSize(width:CGFloat(MAXFLOAT), height:height)
//        
//        let strSize = statusLabelText.boundingRect(with: maxSize, options: .usesLineFragmentOrigin, attributes: attr as? [String : AnyObject], context:nil).size
//        return strSize
//    }
//    public func boundingRectWithStringFont(string:String,font:UIFont) -> CGSize {
//        
//        let attr = NSMutableDictionary.init()
//        attr[NSFontAttributeName] = font
//        let maxSize = CGSize(width:CGFloat(MAXFLOAT), height:CGFloat(MAXFLOAT))
//        let strSize = string.boundingRect(with: maxSize, options: .usesLineFragmentOrigin, attributes: attr as? [String : AnyObject], context:nil).size
//        return strSize
//    }
//    public func formatterCurrency(currency:String) -> String {
//        let formatter = NumberFormatter.init()
//        formatter.numberStyle = .decimal
//        let remainingString = formatter.string(from: NSNumber.init(value: Int(currency)!))
//        return (remainingString?.appending(".00"))!
//    }
//    
//    public func formatterCurrencyWithCGflot(currency:CGFloat) -> String {
//        let formatter = NumberFormatter.init()
//        formatter.numberStyle = .decimal
//        let remainingString = formatter.string(from: NSNumber.init(integerLiteral: Int(currency)))
//        return remainingString!
//    }
//    
//    /**
//     第一个参数是传入一个CGSize结构体;
//     第二个参数options是个配置选项
//     高度计算时就传入NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading
//     如果你是用的String 的方法就有第三个参数：attributes其实就是NSAttributeString的属性，是个字典类型的对象，传入你的字体
//     */
//    
//    public func WidthBoundingRectWithString(string:String,font:UIFont) ->CGSize {
//        
//        let statusLabelText: String = string
//        
//        let size = CGSize(width:CGFloat(MAXFLOAT), height:CGFloat(MAXFLOAT))
//        
//        let attr = NSMutableDictionary.init()
//        attr[NSFontAttributeName] = font
//        
//        let strSize = statusLabelText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: attr as? [String : AnyObject], context:nil).size
//        
//        return strSize
//        
//    }
//    /*
//     显示正在开发中
//     */
//    public func setstateWithProgress() {
//        SVProgressHUD.setBackgroundColor(WHITE_COLOR)
//        SVProgressHUD.setMinimumSize(CGSize(width:100,height:35))
//        SVProgressHUD.setMinimumDismissTimeInterval(3)
//        SVProgressHUD.setMaximumDismissTimeInterval(4)
//        
//    }
//    
//    //邮箱验证
//    static func justEmail(email:String) -> Bool {
//        let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
//        let emailPredicate = NSPredicate(format: "SELF MATCHES %@", emailRegex)
//        return emailPredicate.evaluate(with: email)
//    }
//    //手机号码验证
//    static func justMobile(mobile:String) -> Bool {
//        //手机号以13， 15，18开头，八个 \d 数字字符
//        let phoneRegex = "^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$"
//        let phoneTest = NSPredicate(format: "SELF MATCHES %@", phoneRegex)
//        return phoneTest.evaluate(with:mobile)
//    }
//    
//    //车牌号验证
//    static func justCarNo(carNo:String) -> Bool {
//        let carRegex = "^[A-Za-z]{1}[A-Za-z_0-9]{5}$"
//        let carPredicate = NSPredicate(format: "SELF MATCHES %@", carRegex)
//        return carPredicate.evaluate(with: carNo)
//    }
//    //车型
//    static func justCarType(CarType:String) -> Bool {
//        let CarTypeRegex = "^[A-Za-z]{1}[A-Za-z_0-9]{5}$"
//        let carPredicate = NSPredicate(format: "SELF MATCHES %@", CarTypeRegex)
//        return carPredicate.evaluate(with: CarType)
//    }
//    
//    //用户名
//    static func justUserName(name:String) -> Bool {
//        
//        let userNameRegex = "^[A-Za-z0-9]{6,20}+$"
//        let userNamePredicate = NSPredicate(format: "SELF MATCHES %@", userNameRegex)
//        let peopleName = userNamePredicate.evaluate(with: name)
//        return peopleName
//    }
//    //密码
//    static func justPassword(passWord:String) -> Bool {
//        let passWordRegex = "^[a-zA-Z0-9]{6,20}+$"
//        let passWordPredicate = NSPredicate(format:"SELF MATCHES %@",passWordRegex)
//        return passWordPredicate.evaluate(with:passWord)
//    }
//    
//    //昵称
//    static func justNickname(nickname:String) -> Bool {
//        let nicknameRegex = "^[a-zA-Z0-9]{6,20}+$"
//        let passWordPredicate = NSPredicate(format:"SELF MATCHES %@",nicknameRegex)
//        return passWordPredicate.evaluate(with:nickname)
//    }
//    
//    
//    //身份证号
//    func justIdentityCard(identityCard:String) -> Bool {
//        var flag = false
//        if identityCard.characters.count <= 0 {
//            flag = false
//            return flag
//        }
//        let regex2 = "^(\\d{14}|\\d{17})(\\d|[xX])$"
//        let identityCardPredicate = NSPredicate(format:"SELF MATCHES %@",regex2)
//        return identityCardPredicate.evaluate(with:identityCard)
//    }
//    
//    /************************************手机相关信息****************************************************/
//    /**
//     *  手机型号
//     *
//     *  @return e.g. iPhone
//     */
//    static func phoneModel() -> String {
//        return UIDevice.current.model
//    }
//    
//    /**
//     手机别名*/
//    static func phoneName() -> String {
//        return UIDevice.current.name
//    }
//    
//    /**
//     *  手机系统版本
//     *
//     *  @return e.g. 8.0
//     */
//    static func phoneVersion() -> String {
//        return UIDevice.current.systemVersion
//    }
//    
//    /**
//     bundle是一个目录,其中包含了程序会使用到的资源
//     */
//    static func getBundleInfo() -> NSDictionary {
//        //app应用相关信息的获取
//        return Bundle.main.infoDictionary! as NSDictionary
//    }
//    /*
//     获取版本号
//     */
//    static func getVersion() -> String {
//        let key = "CFBundleVersion"
//        let currentVersion = Bundle.main.object(forInfoDictionaryKey: key)
//        return currentVersion as! String
//    }
//    
//    static func getShortVersion() -> String {
//        
//        let key = "CFBundleShortVersionString"
//        let currentVersion = Bundle.main.object(forInfoDictionaryKey: key)
//        return currentVersion as! String
//    }
//    
//    static func getInfoDictionary() -> NSDictionary {
//        let dic = Bundle.main.infoDictionary
//        return dic!as NSDictionary
//    }
//    
//    /**
//     判断是不是数字
//     */
//    static func deptNumInputShouldNumber(str:String) -> Bool {
//        let regex = "[0-9]*"
//        let pred = NSPredicate(format:"SELF MATCHES %@",regex)
//        if pred.evaluate(with: str) {
//            return true
//        } else {
//            return false
//        }
//    }
//    
//    /****************************银行卡信息************************************************/
//    // 银行卡号转正常号 － 去除4位间的空格
//    static func bankNumToNormalNum(bankCardNumber:String) -> String {
//        return bankCardNumber.replacingOccurrences(of: " ", with: "")
//    }
//    // 正常号转银行卡号 － 增加4位间的空格
//    static func normalNumToBankNum(bankCardNumber:String) -> String {
//        let size : Int = bankCardNumber.characters.count / 4
//        let tmpStrArr = NSMutableArray.init()
//        for n in 0..<size {
//            let start = bankCardNumber.index(bankCardNumber.startIndex, offsetBy: n*4)
//            let end = bankCardNumber.index(bankCardNumber.startIndex, offsetBy: 4)
//            let myRange = start..<end
//            
//            tmpStrArr.add(bankCardNumber.substring(with: myRange))
//        }
//        let startIndex = bankCardNumber.index(bankCardNumber.startIndex, offsetBy: size*4)
//        let endIndex = bankCardNumber.index(bankCardNumber.startIndex, offsetBy: bankCardNumber.characters.count%4)
//        let range = startIndex..<endIndex
//        tmpStrArr.add(bankCardNumber.substring(with: range))
//        
//        let bankCard = tmpStrArr.componentsJoined(by: " ")
//        
//        return bankCard;
//    }
//    
//    /**验证银行卡*/
//    static func IsBankCard(cardNumber:String) -> Bool {
//        if cardNumber.characters.count == 0 {
//            return false
//        }
//        //        var digitsOnly = ""
//        //        let letters = NSCharacterSet.letters
//        //        let digits = NSCharacterSet.decimalDigits
//        //
//        //        for index in cardNumber.unicodeScalars {
//        //            if digits.hasMember(inPlane: UInt8(index.value)) {
//        //                digitsOnly = digitsOnly.appending(index)
//        //            }
//        //        }
//        //        var sum = 0
//        //        var digit = 0
//        //        var addend = 0
//        //        var timesTwo = false
//        //        for i in (0...digitsOnly.characters.count - 1).reversed() {
//        //            digit = digitsOnly.index(i, offsetBy: digitsOnly.startIndex) - "0"
//        //            if (timesTwo)
//        //            {
//        //                addend = digit * 2;
//        //                if (addend > 9) {
//        //                    addend -= 9;
//        //                }
//        //            }
//        //            else {
//        //                addend = digit;
//        //            }
//        //            sum += addend;
//        //            timesTwo = !timesTwo;
//        //        }
//        //
//        //        let modulus = sum % 10;
//        //        return modulus == 0;
//        return true
//    }
//    /**
//     创建静态变量bundle,获取bundle,不可以使用getbundle
//     */
//    static func bundle() -> Bundle {
//        return bundle()
//    }
//    
//    /**
//     userLanguage存储在NSUserDefaults 首次加载检测是否存在,不存在读取AppleLanguages,并赋值给userLanguage
//     */
//    
//    static func initUserLanguage() {
//        
//        var string = SYDSaveTool.valueForKey(defaultName: "userLanguage")
//        if string.length == 0 {
//            //获取系统当前语言版本(中文zh-Hans 英文en)
//            let languages = SYDSaveTool.valueForKey(defaultName: "AppleLanguages")
//            let currentLanguage = languages.object(at: 0)
//            string = currentLanguage as AnyObject
//            SYDSaveTool.setObjectforKey(value: string, defaultName: "userLanguage")
//        }
//        //2.获取文件路径
//        let path = Bundle.main.path(forResource: string as? String, ofType: "lproj")
//        _ = Bundle.init(path: path!)!//生成bundle
//    }
//    
//    /**
//     获取当前应用语言方法
//     */
//    static func setUserlanguage(language:String) {
//        let path = Bundle.main.path(forResource: language, ofType: "lproj")
//        
//        let bundle = Bundle.init(path: path!)
//        print(bundle as Any)
//        SYDSaveTool.setValueForKey(value: language as AnyObject, defaultName: "userLanguage")
//    }
//    static func userLanguage() -> String {
//        let langArr = SYDSaveTool.valueForKey(defaultName: "AppleLanguages")
//        let language = langArr.firstObject
//        return language as! String
//    }
//    static func getCurrentLanguage() -> String {
//        
//        let preferredLang = Bundle.main.preferredLocalizations.first! as NSString
//        //        let preferredLang = (languages! as AnyObject).object(0)
//        print("当前系统语言:\(preferredLang)")
//        
//        switch String(describing: preferredLang) {
//        case "en-US", "en-CN":
//            return "en"//英文
//        case "zh-Hans-US","zh-Hans-CN","zh-Hant-CN","zh-TW","zh-HK","zh-Hans":
//            return "cn"//中文
//        default:
//            return "en"
//        }
//    }
//    
//    /*
//     获取plist文件
//     */
//    static func resourcePathWithFileName(fileName:String,type:String) -> NSDictionary {
//        
//        let path = Bundle.main.path(forResource: fileName, ofType: type)
//        let url = URL(fileURLWithPath:path!)
//        var jsonDic:NSDictionary
//        do {
//            let data = try Data(contentsOf: url)
//            let json:Any = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers)
//            
//            jsonDic = json as! NSDictionary
//            return jsonDic
//        } catch let error as Error!{
//            print("读取本地数据出现错误！",error)
//        }
//        return NSDictionary()
//    }
//    
//    /**
//     ios通过图片的URL地址，从网络上获取图片(UIImage类型)
//     @param fileURL 图片url
//     @return uiimage
//     */
//    static func getImageFromURL(fileURL:String) -> UIImage {
//        let result : UIImage
//        let data = NSData.init(contentsOf: URL.init(string: fileURL)!)
//        result = UIImage.init(data: data! as Data)!
//        return result
//    }
//    /*
//     获取ip地址
//     */
//    static func getIPAddress() -> String? {
//        var address: String?
//        // get list of all interfaces on the local machine
//        var ifaddr: UnsafeMutablePointer<ifaddrs>? = nil
//        
//        guard getifaddrs(&ifaddr) == 0 else {
//            return nil
//        }
//        guard let firstAddr = ifaddr else {
//            return nil
//        }
//        for ifptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) {
//            
//            let interface = ifptr.pointee
//            
//            // Check for IPV4 or IPV6 interface
//            let addrFamily = interface.ifa_addr.pointee.sa_family
//            if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) {
//                // Check interface name
//                let name = String(cString: interface.ifa_name)
//                if name == "en0" {
//                    // Convert interface address to a human readable string
//                    var addr = interface.ifa_addr.pointee
//                    var hostName = [CChar](repeating: 0, count: Int(NI_MAXHOST))
//                    getnameinfo(&addr,
//                                socklen_t(interface.ifa_addr.pointee.sa_len),
//                                &hostName, socklen_t(hostName.count), nil, socklen_t(0), NI_NUMERICHOST)
//                    address = String(cString: hostName)
//                }
//            }
//        }
//        freeifaddrs(ifaddr)
//        return address
//    }
//    
//    //获取当前控制器
//    static func topViewController() -> UIViewController {
//        var resultVC:UIViewController
//        resultVC = self._topViewController(vc: (UIApplication.shared.keyWindow?.rootViewController)!)
//        while (resultVC.presentedViewController != nil) {
//            resultVC = self._topViewController(vc: resultVC.presentedViewController!)
//        }
//        return resultVC
//    }
//    
//    static func _topViewController(vc:UIViewController) -> UIViewController {
//        
//        if vc.isKind(of:UINavigationController.self) {
//            return self._topViewController(vc: (vc as? UINavigationController)!.topViewController!)
//        } else if vc.isKind(of: UITabBarController.self){
//            return self._topViewController(vc: (vc as? UITabBarController)!.selectedViewController!)
//        }else {
//            return vc
//        }
//    }
//    
//    
//    static func widthOfStringFontHeight(string:String,font:UIFont,height:CGFloat) -> CGFloat {
//        
//        let dict : NSDictionary = NSDictionary(object:font, forKey:NSFontAttributeName as NSCopying)
//        let rect: CGRect = string.boundingRect(with:CGSize(width:CGFloat.greatestFiniteMagnitude,height:height) , options:.truncatesLastVisibleLine ,attributes:dict as? [String : Any],context: nil)
//        return rect.size.width
//    }
//    static func heightOfStringFontWidth(string:String,font:UIFont,width:CGFloat) -> CGFloat {
//        var bounds: CGRect
//        let parameterDict: [NSObject : AnyObject] = NSDictionary(object: font, forKey: NSFontAttributeName as NSCopying) as [NSObject : AnyObject]
//        bounds = string.boundingRect(with:CGSize(width:width,height:CGFloat.greatestFiniteMagnitude), options: .truncatesLastVisibleLine, attributes: parameterDict as? [String : Any],context: nil)
//        return bounds.size.height
//    }
//    
//    
//}
//
////MARK: - UIDevice延展
//public extension UIDevice {
//    
//    var modelName: String {
//        var systemInfo = utsname()
//        uname(&systemInfo)
//        let machineMirror = Mirror(reflecting: systemInfo.machine)
//        let identifier = machineMirror.children.reduce("") { identifier, element in
//            guard let value = element.value as? Int8, value != 0 else { return identifier }
//            return identifier + String(UnicodeScalar(UInt8(value)))
//        }
//        
//        switch identifier {
//        case "iPod5,1":                                 return "iPod Touch 5"
//        case "iPod7,1":                                 return "iPod Touch 6"
//        case "iPhone3,1", "iPhone3,2", "iPhone3,3":     return "iPhone 4"
//        case "iPhone4,1":                               return "iPhone 4s"
//        case "iPhone5,1", "iPhone5,2":                  return "iPhone 5"
//        case "iPhone5,3", "iPhone5,4":                  return "iPhone 5c"
//        case "iPhone6,1", "iPhone6,2":                  return "iPhone 5s"
//        case "iPhone7,2":                               return "iPhone 6"
//        case "iPhone7,1":                               return "iPhone 6 Plus"
//        case "iPhone8,1":                               return "iPhone 6s"
//        case "iPhone8,2":                               return "iPhone 6s Plus"
//        case "iPhone8,4":                               return "iPhone SE"
//        case "iPhone9,1":                               return "iPhone 7"
//        case "iPhone9,2":                               return "iPhone 7 Plus"
//        case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2"
//        case "iPad3,1", "iPad3,2", "iPad3,3":           return "iPad 3"
//        case "iPad3,4", "iPad3,5", "iPad3,6":           return "iPad 4"
//        case "iPad4,1", "iPad4,2", "iPad4,3":           return "iPad Air"
//        case "iPad5,3", "iPad5,4":                      return "iPad Air 2"
//        case "iPad2,5", "iPad2,6", "iPad2,7":           return "iPad Mini"
//        case "iPad4,4", "iPad4,5", "iPad4,6":           return "iPad Mini 2"
//        case "iPad4,7", "iPad4,8", "iPad4,9":           return "iPad Mini 3"
//        case "iPad5,1", "iPad5,2":                      return "iPad Mini 4"
//        case "iPad6,7", "iPad6,8":                      return "iPad Pro"
//        case "AppleTV5,3":                              return "Apple TV"
//        case "i386", "x86_64":                          return "Simulator"
//        default:                                        return identifier
//        }
//    }
//    
//    
//}
